//
//  LoginViewController.m
//  MateAdv
//
//  Created by 茶 on 2023/9/18.
//

#import "LoginViewController.h"
#import "MAButton.h"
#import <AuthenticationServices/AuthenticationServices.h>

#import <MPITextKit/MPITextKit.h>

#import <UMCommon/UMCommon.h>
#import <UMVerify/UMVerify.h>
// U-Share核心SDK
#import <UMShare/UMShare.h>


@interface LoginViewController () <MPILabelDelegate, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (nonatomic, strong) UIButton *checkBtn;
@property (nonatomic, strong) UMCustomModel *model;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    [self initInterface];
    [self checkEnv];
}

- (void)initInterface {
    [UIImageView ma_imgViewWithSuperView:self.view imgName:@"Login_Back" makeMasonryBlock:^(MASConstraintMaker * _Nonnull make) {
        make.left.top.right.mas_equalTo(0);
    }];
    
    [UIImageView ma_imgViewWithSuperView:self.view imgName:@"Login_Logo" makeMasonryBlock:^(MASConstraintMaker * _Nonnull make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ma_offset(77);
    }];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [loginBtn setTitle:@"本机号码一键登录" forState:UIControlStateNormal];
    [loginBtn setBackgroundColor:MAColor(@"#FF0071")];
    loginBtn.titleLabel.font = MAFontScaleMedium(16);
    loginBtn.layer.cornerRadius = MARatioWidth(24);
    loginBtn.clipsToBounds = YES;
    [loginBtn addTarget:self action:@selector(oneClickLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).ma_offset(334);
        make.height.ma_offset(48);
        make.width.ma_offset(327);
    }];
    
    NSArray *titles = @[@"苹果登录", @"微信登录", @"QQ登录", @"游客登录"];
    NSArray *imgs = @[@"Login_Apple", @"Login_Weixin", @"Login_QQ", @"Login_Guest"];
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSignInWithAppleStateChanged:) name:ASAuthorizationAppleIDProviderCredentialRevokedNotification object:nil];
    } else {
        titles = @[@"微信登录", @"QQ登录", @"游客登录"];
        imgs = @[@"Login_Weixin", @"Login_QQ", @"Login_Guest"];
    }
    
    NSMutableArray *btns = [NSMutableArray arrayWithCapacity:titles.count];
    for (int i = 0; i < titles.count; i++) {
        MAButton *button = [MAButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, MARatioWidth(60), MARatioHeight(70));
        if (titles.count < 4) {
            button.tag = i + 1;
        } else {
            button.tag = i;
        }
        [button.titleLabel setFont:MAFontScaleRegular(12)];
        [button setImage:[UIImage imageNamed:imgs[i]] forState:UIControlStateNormal];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:MARatioWidth(8)];
        [button setTitleColor:MAColor(@"#191919") forState:UIControlStateNormal];
        [btns addObject:button];
        [button addTarget:self action:@selector(loginEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).ma_offset(-70);
            make.height.ma_offset(70);
        }];
    }
    [btns mas_distributeRatioViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:60 leadSpacing:42 tailSpacing:42];
    
    _checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_checkBtn setImage:[UIImage imageNamed:@"Login_Uncheck"] forState:UIControlStateNormal];
    [_checkBtn setImage:[UIImage imageNamed:@"Login_Check"] forState:UIControlStateSelected];
    [_checkBtn addTarget:self action:@selector(checkEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_checkBtn];
    [_checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).ma_offset(-4);
        make.left.ma_offset(33);
    }];
    
    NSString *content = @"勾选即同意《用户隐私政策》和《用户服务协议》";
    NSMutableAttributedString *atrString = [[NSMutableAttributedString alloc] initWithString:content
                                                                                  attributes:@{NSFontAttributeName: MAFontScaleRegular(13)}];
    MPITextLink *privacy = [MPITextLink linkWithValue:[NSURL URLWithString:kPrivacyURL]];
    MPITextLink *agreement = [MPITextLink linkWithValue:[NSURL URLWithString:kUserAgreementURL]];

    NSRange privacyRange = [content rangeOfString:@"《用户隐私政策》"];
    NSRange agreementRange = [content rangeOfString:@"《用户服务协议》"];
    [atrString addAttribute:MPITextLinkAttributeName value:privacy range:privacyRange];
    [atrString addAttribute:MPITextLinkAttributeName value:agreement range:agreementRange];
    [atrString addAttribute:NSForegroundColorAttributeName value:MAColor(@"#FF0071") range:privacyRange];
    [atrString addAttribute:NSForegroundColorAttributeName value:MAColor(@"#FF0071") range:agreementRange];
    [atrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:privacyRange];
    [atrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:agreementRange];
    
    MPILabel *contentLabel = [MPILabel new];
    contentLabel.delegate = self;
    contentLabel.attributedText = atrString;
    contentLabel.font = MAFontScaleRegular(13);
    contentLabel.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ma_offset(58);
        make.right.ma_offset(0);
        make.centerY.mas_equalTo(self.checkBtn);
    }];
}

- (void)checkEnv {
    //检查环境
    [UMCommonHandler checkEnvAvailableWithAuthType:UMPNSAuthTypeLoginToken complete:^(NSDictionary*_Nullable resultDic){
    //判断检查环境是否成功

    }];
}

- (void)oneClickLogin {
    if (!_checkBtn.isSelected) {
        [self.view makeToast:@"请先点击同意协议"];
        return;
    }
    MAWeakify(self);
    //1. 调⽤用取号接⼝，加速授权⻚的弹起
    [UMCommonHandler accelerateLoginPageWithTimeout:5 complete:^(NSDictionary * _Nonnull resultDic) {
        MAStrongify(self);
        if ([resultDic[@"resultCode"] intValue] != 600000) {
            [self.view makeToast:resultDic[@"msg"]];
            return;
        }
        //设置样式
        [UMCommonHandler getLoginTokenWithTimeout:30 controller:weak_self model:self.model complete:^(NSDictionary * _Nonnull resultDic) {
            NSString *code = [resultDic objectForKey:@"resultCode"];
            if([PNSCodeSuccess isEqualToString:code]){
                //点击登录按钮获取登录Token成功回调
                NSString*token = [resultDic objectForKey:@"token"];
                //拿Token去服务器器换⼿机号
                [self loginRequestWithType:3 params:@{@"unionid" : token}];
            }else if([PNSCodeLoginControllerClickChangeBtn isEqualToString:code]) {
                
            }
        }];
    }];
    
   
}

- (void)checkEvent:(UIButton *)button {
    button.selected = !button.isSelected;
}

- (void)loginEvent:(UIButton *)button {
    NSUInteger index = button.tag;
    if (!_checkBtn.isSelected) {
        [self.view makeToast:@"请先点击同意协议"];
        return;
    }
    if (index == 0) {
        [self authorizationAppleID];
    } else if (index == 1) {
        [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
    } else if (index == 2) {
        [self getUserInfoForPlatform:UMSocialPlatformType_QQ];
    } else if (index == 3) {
        [self loginRequestWithType:0 params:nil];
    }
}

- (void)loginRequestWithType:(NSUInteger)type params:(NSDictionary *)params {
    MAWeakify(self);
    [self.view makeToastActivity:CSToastPositionCenter];
    [ReqManager loginWithType:type params:params successed:^(id _Nonnull object) {
        MAStrongify(self);
        [self.view hideToastActivity];
        if ([object containKey:@"token"]) {
            [kUserDefaults setObject:object[@"token"] forKey:kUserToken];
            [kUserDefaults setObject:object[@"user_info"] forKey:kUserInfo];
            if (type == 3) {
                [self dismissViewControllerAnimated:YES completion:^{
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
    } failed:^(NSError * _Nonnull error) {
        MAStrongify(self);
        [self.view hideToastActivity];
        [self.view makeToast:error.localizedDescription];
    }];
}

- (void)authorizationAppleID{
    if (@available(iOS 13.0, *)) {
        // 基于用户的Apple ID授权用户，生成用户授权请求的一种机制
        ASAuthorizationAppleIDProvider * appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        // 创建新的AppleID 授权请求
        ASAuthorizationAppleIDRequest * authAppleIDRequest = [appleIDProvider createRequest];
        authAppleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        NSMutableArray <ASAuthorizationRequest *> * array = [NSMutableArray arrayWithCapacity:2];
        if (authAppleIDRequest) {
            [array addObject:authAppleIDRequest];
        }
        NSArray <ASAuthorizationRequest *> * requests = [array copy];
        // 由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
        ASAuthorizationController * authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:requests];
         // 设置授权控制器通知授权请求的成功与失败的代理
        authorizationController.delegate = self;
        // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
        authorizationController.presentationContextProvider = self;
        // 在控制器初始化期间启动授权流
        [authorizationController performRequests];
    }
}

#import <UMShare/UMShare.h>
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    NSUInteger index = 1;
    if (platformType == UMSocialPlatformType_QQ) {
        index = 2;
    }
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
        UMSocialUserInfoResponse *resp = result;
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        if (resp.uid) {
            [self loginRequestWithType:index params:@{@"unionid" : resp.uid}];
        }
//        NSLog(@" openid: %@", resp.openid);
//        NSLog(@" accessToken: %@", resp.accessToken);
//        NSLog(@" refreshToken: %@", resp.refreshToken);
//        NSLog(@" expiration: %@", resp.expiration);
//        // 用户数据
//        NSLog(@" name: %@", resp.name);
//        NSLog(@" iconurl: %@", resp.iconurl);
//        NSLog(@" gender: %@", resp.unionGender);
//        // 第三方平台SDK原始数据
//        NSLog(@" originalResponse: %@", resp.originalResponse);
    }];
}

#pragma mark- MPILabelDelegate
- (void)label:(MPILabel *)label didInteractWithLink:(MPITextLink *)link forAttributedText:(NSAttributedString *)attributedText inRange:(NSRange)characterRange interaction:(MPITextItemInteraction)interaction {
    if ([link.value isKindOfClass:NSURL.class]) {
        [UIApplication.sharedApplication openURL:(NSURL *)link.value options:@{} completionHandler:nil];
    }
}

#pragma mark- ASAuthorizationControllerDelegate
// 授权成功
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential * credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
        NSLog(@"identityToken: %@", identityToken);
        if (identityToken) {
            [self loginRequestWithType:5 params:@{@"unionid" : identityToken}];
        }
    }
//    else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
//        // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
//        // 用户登录使用现有的密码凭证
//        ASPasswordCredential * passwordCredential = (ASPasswordCredential *)authorization.credential;
//        // 密码凭证对象的用户标识 用户的唯一标识
//        NSString * user = passwordCredential.user;
//
//    }
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    NSLog(@"%@", errorMsg);
}

#pragma mark- ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    return self.view.window;
}
#pragma mark- apple授权状态 更改通知
- (void)handleSignInWithAppleStateChanged:(NSNotification *)notification{
    NSLog(@"%@", notification.userInfo);
}
- (void)dealloc {
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:ASAuthorizationAppleIDProviderCredentialRevokedNotification object:nil];
    }
}


- (UMCustomModel *)model {
    if (_model) return _model;
    UIColor *baseColor = MAColor(@"#FF0071");
    UMCustomModel*model =[[UMCustomModel alloc] init];
    model.alertCornerRadiusArray =@[@10,@10,@10,@10];
    model.alertTitleBarColor = UIColor.clearColor;
    model.alertTitle = [[NSAttributedString alloc] initWithString:@""];
    model.alertCloseImage = [UIImage imageNamed:@"icon_close_light"];
    model.privacyNavColor = baseColor;
    model.privacyNavBackImage = [UIImage imageNamed:@"icon_nav_back_light"];
    model.privacyNavTitleFont = [UIFont systemFontOfSize:20.0];
    model.privacyNavTitleColor = UIColor.whiteColor;
    model.logoImage = [UIImage imageNamed:@"Launch_Logo"];
    model.sloganIsHidden = YES;
    model.numberColor = baseColor;
    model.numberFont = MAFontScaleMedium(30);
    model.loginBtnText =[[NSAttributedString alloc] initWithString:@"一键登录" attributes:@{NSForegroundColorAttributeName:UIColor.whiteColor,NSFontAttributeName:MAFontScaleMedium(16)}];
    model.privacyColors = @[UIColor.lightGrayColor, baseColor];
    model.privacyAlignment =NSTextAlignmentCenter;
    model.privacyFont = MAFontScaleRegular(13);
    model.privacyOperatorPreText =@"《";
    model.privacyOperatorSufText =@"》";
    model.checkBoxWH = 17.0;
    model.changeBtnIsHidden = YES;
    
    CGFloat ratio = MAX(SCREEN_WIDTH, SCREEN_HEIGHT) / 667.0;
    model.contentViewFrameBlock =^CGRect(CGSize screenSize,CGSize contentSize,CGRect frame){
        CGFloat alertX =0;
        CGFloat alertY =0;
        CGFloat alertWidth =0;
        CGFloat alertHeight =0;
        alertX = 20 * ratio;
        alertWidth = screenSize.width - alertX *2;
        alertY = 100 * ratio;
        alertHeight = screenSize.height - alertY *2;
        
        return CGRectMake(alertX, alertY, alertWidth, alertHeight);
    };
    // 仅支持竖屏
    model.supportedInterfaceOrientations =UIInterfaceOrientationMaskPortrait;
    _model = model;
    return _model;

}
@end
